<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';

import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

import PetSelector from '../components/PetSelector.vue';
import ResultDetailModal from './components/ResultDetailModal.vue';
import TestDetailModal from './components/TestDetailModal.vue';
import TestItemModal from './components/TestItemModal.vue';

// 接口定义
interface Pet {
  id: string;
  name: string;
  type: string;
  breed: string;
  age: string;
  gender: string;
  ownerName: string;
  ownerPhone: string;
  doctor: string;
  phone: string;
}

interface TestItem {
  id: string;
  name: string;
  category: string;
  device: string;
  status: 'completed' | 'error' | 'pending' | 'processing';
  result?: string;
  unit?: string;
  reference?: string;
  abnormal?: boolean;
  createTime: string;
  completeTime?: string;
}

interface TestOrder {
  id: string;
  orderName: string;
  petId: string;
  createTime: string;
  status: 'completed' | 'pending' | 'processing';
  testItems: TestItem[];
  remarks?: string;
}

interface Device {
  id: string;
  name: string;
  type: string;
  icon: string;
  status: 'offline' | 'online';
  lastConnectTime?: string;
}

interface TestResult {
  id: string;
  testItemId: string;
  testItemName: string;
  result: string;
  unit: string;
  reference: string;
  abnormal: boolean;
  status: 'completed' | 'pending';
  createTime: string;
  completeTime?: string;
}

// 响应式数据
const activeTab = ref('today');
const searchQuery = ref('');
const selectedPet = ref<null | Pet>(null);
const selectedOrder = ref<null | TestOrder>(null);
const selectedTestItem = ref<null | TestItem>(null);
const selectedResult = ref<null | TestResult>(null);
const showTestItemModal = ref(false);
const showTestDetailModal = ref(false);
const showResultDetailModal = ref(false);
const resultFilter = ref('all');

// 模拟数据
const pets = ref<Pet[]>([
  {
    id: '1',
    name: '小白',
    type: 'dog',
    breed: '金毛',
    age: '3岁',
    gender: '公',
    ownerName: '张三',
    ownerPhone: '13800138001',
    doctor: '李医生',
    phone: '13800138001',
  },
  {
    id: '2',
    name: '咪咪',
    type: 'cat',
    breed: '英短',
    age: '2岁',
    gender: '母',
    ownerName: '李四',
    ownerPhone: '13800138002',
    doctor: '王医生',
    phone: '13800138002',
  },
]);

const testOrders = ref<TestOrder[]>([]);

const devices = ref<Device[]>([
  {
    id: '1',
    name: '血常规分析仪',
    type: 'blood',
    icon: '🩸',
    status: 'online',
    lastConnectTime: dayjs()
      .subtract(5, 'minute')
      .format('YYYY-MM-DD HH:mm:ss'),
  },
  {
    id: '2',
    name: '生化分析仪',
    type: 'biochemistry',
    icon: '🧪',
    status: 'online',
    lastConnectTime: dayjs()
      .subtract(2, 'minute')
      .format('YYYY-MM-DD HH:mm:ss'),
  },
  {
    id: '3',
    name: '电解质分析仪',
    type: 'electrolyte',
    icon: '⚡',
    status: 'offline',
  },
  {
    id: '4',
    name: '血气分析仪',
    type: 'blood_gas',
    icon: '💨',
    status: 'online',
    lastConnectTime: dayjs()
      .subtract(1, 'minute')
      .format('YYYY-MM-DD HH:mm:ss'),
  },
  {
    id: '5',
    name: '显微镜',
    type: 'microscope',
    icon: '🔬',
    status: 'online',
    lastConnectTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  },
]);

// 表格列定义
const testColumns = [
  { title: '检验项目', dataIndex: 'name', key: 'name' },
  { title: '设备', dataIndex: 'device', key: 'device' },
  { title: '状态', key: 'status' },
  { title: '结果', key: 'result' },
  { title: '操作', key: 'action' },
];

const resultColumns = [
  { title: '检验项目', dataIndex: 'testItemName', key: 'testItemName' },
  { title: '结果', dataIndex: 'result', key: 'result' },
  { title: '参考值', dataIndex: 'reference', key: 'reference' },
  { title: '状态', key: 'status' },
  { title: '操作', key: 'action' },
];

// 计算属性
const filteredResults = computed(() => {
  if (!selectedOrder.value) return [];

  const results = selectedOrder.value.testItems.map((item) => ({
    id: item.id,
    testItemId: item.id,
    testItemName: item.name,
    result: item.result || '--',
    unit: item.unit || '',
    reference: item.reference || '--',
    abnormal: item.abnormal || false,
    status: item.status === 'completed' ? 'completed' : 'pending',
    createTime: item.createTime,
    completeTime: item.completeTime,
  }));

  if (resultFilter.value === 'all') return results;
  return results.filter((result) => result.status === resultFilter.value);
});

// 方法
const selectPet = (pet: null | Pet) => {
  selectedPet.value = pet;
  if (pet) {
    loadTestOrders(pet.id);
    // 默认选择第一个宠物
    if (pets.value.length > 0 && !selectedPet.value) {
      selectPet(pets.value[0]);
    }
  } else {
    testOrders.value = [];
    selectedOrder.value = null;
  }
};

const loadTestOrders = (petId: string) => {
  // 模拟加载检验单数据
  testOrders.value = [
    {
      id: '1',
      orderName: `TO${dayjs().format('YYYYMMDD')}001`,
      petId,
      createTime: dayjs().subtract(1, 'hour').format('YYYY-MM-DD HH:mm:ss'),
      status: 'completed',
      testItems: [
        {
          id: '1',
          name: '血常规',
          category: 'blood',
          device: '血常规分析仪',
          status: 'completed',
          result: '正常',
          unit: '',
          reference: '正常范围',
          abnormal: false,
          createTime: dayjs().subtract(1, 'hour').format('YYYY-MM-DD HH:mm:ss'),
          completeTime: dayjs()
            .subtract(30, 'minute')
            .format('YYYY-MM-DD HH:mm:ss'),
        },
        {
          id: '2',
          name: '血糖',
          category: 'biochemistry',
          device: '生化分析仪',
          status: 'completed',
          result: '5.2',
          unit: 'mmol/L',
          reference: '3.9-6.1',
          abnormal: false,
          createTime: dayjs().subtract(1, 'hour').format('YYYY-MM-DD HH:mm:ss'),
          completeTime: dayjs()
            .subtract(20, 'minute')
            .format('YYYY-MM-DD HH:mm:ss'),
        },
      ],
    },
    {
      id: '2',
      orderName: `TO${dayjs().format('YYYYMMDD')}002`,
      petId,
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      status: 'processing',
      testItems: [
        {
          id: '3',
          name: '血气分析',
          category: 'blood_gas',
          device: '血气分析仪',
          status: 'processing',
          createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        },
      ],
    },
  ];

  // 默认选择最新的检验单
  if (testOrders.value.length > 0) {
    selectOrder(testOrders.value[0]);
  }
};

const selectOrder = (order: TestOrder) => {
  selectedOrder.value = order;
};

const createTestOrder = () => {
  if (!selectedPet.value) {
    message.warning('请先选择宠物');
    return;
  }

  const newOrder: TestOrder = {
    id: Date.now().toString(),
    orderName: `TO${dayjs().format(
      'YYYYMMDD',
    )}${String(testOrders.value.length + 1).padStart(3, '0')}`,
    petId: selectedPet.value.id,
    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    status: 'pending',
    testItems: [],
  };

  testOrders.value.unshift(newOrder);
  selectOrder(newOrder);
  message.success('检验单创建成功！');
};

const addTestItem = () => {
  if (!selectedOrder.value) {
    message.warning('请先选择检验单');
    return;
  }
  showTestItemModal.value = true;
};

const handleTestItemSuccess = (items: TestItem[]) => {
  if (!selectedOrder.value) return;

  items.forEach((item) => {
    selectedOrder.value!.testItems.push({
      ...item,
      id: Date.now().toString() + Math.random().toString(36).slice(2, 11),
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    });
  });

  showTestItemModal.value = false;
  message.success(`成功添加 ${items.length} 个检验项目！`);
};

const viewTestDetail = (item: TestItem) => {
  selectedTestItem.value = item;
  showTestDetailModal.value = true;
};

const viewResultDetail = (result: TestResult) => {
  selectedResult.value = result;
  showResultDetailModal.value = true;
};

const connectDevice = (device: Device) => {
  if (device.status === 'offline') {
    message.warning('设备离线，无法连接');
    return;
  }

  device.lastConnectTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
  message.success(`已连接到${device.name}`);
};

const refreshDeviceStatus = () => {
  // 模拟刷新设备状态
  devices.value.forEach((device) => {
    if (Math.random() > 0.8) {
      device.status = device.status === 'online' ? 'offline' : 'online';
    }
  });
  message.success('设备状态已刷新');
};

const printReport = () => {
  message.info('打印功能开发中...');
};

const saveOrder = () => {
  message.success('检验单保存成功！');
};

const closePetTab = () => {
  selectedPet.value = null;
  testOrders.value = [];
  selectedOrder.value = null;
};

const handlePetSearch = (query: string) => {
  searchQuery.value = query;
};

const handleTabChange = (tab: string) => {
  activeTab.value = tab;
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    pending: 'orange',
    processing: 'blue',
    completed: 'green',
    error: 'red',
  };
  return colorMap[status] || 'default';
};

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    pending: '待检验',
    processing: '检验中',
    completed: '已完成',
    error: '异常',
  };
  return textMap[status] || status;
};

// 生命周期
onMounted(() => {
  // 默认选择第一个宠物
  if (pets.value.length > 0) {
    selectPet(pets.value[0]);
  }
});

// 模拟实时数据更新
setInterval(() => {
  if (selectedOrder.value) {
    selectedOrder.value.testItems.forEach((item) => {
      if (item.status === 'processing' && Math.random() > 0.7) {
        item.status = 'completed';
        item.completeTime = dayjs().format('YYYY-MM-DD HH:mm:ss');

        // 模拟生成结果
        if (item.name === '血气分析') {
          item.result = '7.35';
          item.unit = 'pH';
          item.reference = '7.35-7.45';
          item.abnormal = false;
        }
      }
    });
  }
}, 5000);
</script>

<template>
  <div class="laboratory-container">
    <!-- 左侧：宠物信息 -->
    <div class="left-panel">
      <div class="panel-header">
        <h3>宠物信息</h3>
        <a-button type="primary" size="small" @click="createTestOrder">
          + 开具检验单
        </a-button>
      </div>

      <div v-if="selectedPet" class="pet-info-section">
        <div class="pet-tab">
          <span class="pet-name"
            >{{ selectedPet.name }}({{ selectedPet.ownerName }})</span
          >
          <a-button type="text" size="small" @click="closePetTab">×</a-button>
        </div>

        <!-- 检验单列表 -->
        <div class="test-orders">
          <div class="section-header">
            <h4>检验单列表</h4>
          </div>
          <div class="order-list">
            <div
              v-for="order in testOrders"
              :key="order.id"
              class="order-item"
              :class="{ active: selectedOrder?.id === order.id }"
              @click="selectOrder(order)"
            >
              <div class="order-info">
                <div class="order-name">{{ order.orderName }}</div>
                <div class="order-time">{{ order.createTime }}</div>
              </div>
              <div class="order-status">
                <a-tag
                  :color="order.status === 'completed' ? 'green' : 'orange'"
                >
                  {{ order.status === 'completed' ? '已完成' : '进行中' }}
                </a-tag>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-else class="empty-state">
        <div class="empty-icon">🐕</div>
        <div class="empty-text">请选择宠物开具检验单</div>
      </div>
    </div>

    <!-- 中间：检验详情 -->
    <div class="center-panel">
      <div v-if="selectedOrder" class="test-detail">
        <div class="detail-header">
          <div class="header-left">
            <h2>检验单详情</h2>
            <span class="order-info">单号: {{ selectedOrder.orderName }}</span>
          </div>
          <div class="header-right">
            <a-button
              type="default"
              @click="printReport"
              style="margin-right: 8px"
              title="打印"
            >
              🖨️
            </a-button>
            <a-button type="primary" @click="saveOrder">保存</a-button>
          </div>
        </div>

        <div class="test-form">
          <!-- 检验项目 -->
          <div class="form-section">
            <div class="section-header">
              <h3>检验项目</h3>
              <a-button type="primary" size="small" @click="addTestItem">
                + 添加项目
              </a-button>
            </div>

            <a-table
              :columns="testColumns"
              :data-source="selectedOrder.testItems"
              :pagination="false"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                  <a-tag :color="getStatusColor(record.status)">
                    {{ getStatusText(record.status) }}
                  </a-tag>
                </template>
                <template v-else-if="column.key === 'result'">
                  <div
                    v-if="record.status === 'completed'"
                    class="result-display"
                  >
                    <span class="result-value">{{ record.result }}</span>
                    <span class="result-unit">{{ record.unit }}</span>
                    <span v-if="record.reference" class="reference-range">
                      (参考值: {{ record.reference }})
                    </span>
                  </div>
                  <span v-else class="pending-text">等待结果...</span>
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-button
                    type="text"
                    size="small"
                    @click="viewTestDetail(record)"
                  >
                    查看详情
                  </a-button>
                </template>
              </template>
            </a-table>
          </div>

          <!-- 设备状态 -->
          <div class="form-section">
            <div class="section-header">
              <h3>设备状态</h3>
              <a-button
                type="default"
                size="small"
                @click="refreshDeviceStatus"
              >
                🔄 刷新
              </a-button>
            </div>

            <div class="device-grid">
              <div
                v-for="device in devices"
                :key="device.id"
                class="device-card"
                :class="{
                  online: device.status === 'online',
                  offline: device.status === 'offline',
                }"
              >
                <div class="device-icon">{{ device.icon }}</div>
                <div class="device-info">
                  <div class="device-name">{{ device.name }}</div>
                  <div class="device-status">
                    <a-tag
                      :color="device.status === 'online' ? 'green' : 'red'"
                    >
                      {{ device.status === 'online' ? '在线' : '离线' }}
                    </a-tag>
                  </div>
                </div>
                <div class="device-actions">
                  <a-button
                    type="text"
                    size="small"
                    @click="connectDevice(device)"
                    :disabled="device.status === 'offline'"
                  >
                    连接
                  </a-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 检验结果 -->
          <div class="form-section">
            <div class="section-header">
              <h3>检验结果</h3>
              <a-radio-group v-model:value="resultFilter" size="small">
                <a-radio-button value="all">全部</a-radio-button>
                <a-radio-button value="completed">已出报告</a-radio-button>
                <a-radio-button value="pending">未出报告</a-radio-button>
              </a-radio-group>
            </div>

            <a-table
              :columns="resultColumns"
              :data-source="filteredResults"
              :pagination="false"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                  <a-tag
                    :color="record.status === 'completed' ? 'green' : 'orange'"
                  >
                    {{
                      record.status === 'completed' ? '已出报告' : '未出报告'
                    }}
                  </a-tag>
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-button
                    type="text"
                    size="small"
                    @click="viewResultDetail(record)"
                  >
                    查看详情
                  </a-button>
                </template>
              </template>
            </a-table>
          </div>
        </div>
      </div>

      <div v-else class="empty-state">
        <div class="empty-icon">🔬</div>
        <div class="empty-text">请选择检验单查看详情</div>
      </div>
    </div>

    <!-- 右侧：宠物选择 -->
    <div class="right-panel">
      <PetSelector
        :active-tab="activeTab"
        :search-query="searchQuery"
        @pet-select="selectPet"
        @search="handlePetSearch"
        @tab-change="handleTabChange"
      />
    </div>

    <!-- 添加检验项目模态框 -->
    <TestItemModal
      :visible="showTestItemModal"
      @update:visible="showTestItemModal = $event"
      @success="handleTestItemSuccess"
    />

    <!-- 检验详情模态框 -->
    <TestDetailModal
      :visible="showTestDetailModal"
      :test-item="selectedTestItem"
      @update:visible="showTestDetailModal = $event"
    />

    <!-- 结果详情模态框 -->
    <ResultDetailModal
      :visible="showResultDetailModal"
      :result="selectedResult"
      @update:visible="showResultDetailModal = $event"
    />
  </div>
</template>

<style scoped>
.laboratory-container {
  display: flex;
  height: 100vh;
  background: #f5f5f5;
}

.left-panel {
  display: flex;
  flex-direction: column;
  width: 320px;
  background: white;
  border-right: 1px solid #e8e8e8;
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.pet-info-section {
  display: flex;
  flex: 1;
  flex-direction: column;
}

.pet-tab {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #f0f8ff;
  border-bottom: 1px solid #e8e8e8;
}

.pet-name {
  font-weight: bold;
  color: #333;
}

.test-orders {
  flex: 1;
  padding: 16px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.section-header h4 {
  margin: 0;
  font-size: 14px;
  color: #333;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.order-item {
  padding: 12px;
  cursor: pointer;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  transition: all 0.3s;
}

.order-item:hover {
  background: #f0f8ff;
  border-color: #1890ff;
}

.order-item.active {
  background: #e6f7ff;
  border-color: #1890ff;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.order-name {
  font-weight: bold;
  color: #333;
}

.order-time {
  font-size: 12px;
  color: #666;
}

.order-status {
  margin-top: 8px;
}

.center-panel {
  display: flex;
  flex: 1;
  flex-direction: column;
  background: white;
}

.test-detail {
  display: flex;
  flex: 1;
  flex-direction: column;
}

.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  border-bottom: 1px solid #e8e8e8;
}

.header-left h2 {
  margin: 0 0 4px;
  color: #333;
}

.order-info {
  font-size: 14px;
  color: #666;
}

.test-form {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 32px;
}

.form-section h3 {
  margin: 0 0 16px;
  font-size: 16px;
  color: #333;
}

.device-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.device-card {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  transition: all 0.3s;
}

.device-card.online {
  background: #f6ffed;
  border-color: #52c41a;
}

.device-card.offline {
  background: #fff2f0;
  border-color: #ff4d4f;
}

.device-icon {
  margin-right: 12px;
  font-size: 24px;
}

.device-info {
  flex: 1;
}

.device-name {
  margin-bottom: 4px;
  font-weight: bold;
  color: #333;
}

.device-actions {
  margin-left: 8px;
}

.result-display {
  display: flex;
  gap: 4px;
  align-items: center;
}

.result-value {
  font-weight: bold;
  color: #333;
}

.result-unit {
  font-size: 12px;
  color: #666;
}

.reference-range {
  font-size: 12px;
  color: #999;
}

.pending-text {
  font-style: italic;
  color: #999;
}

.right-panel {
  width: 280px;
  overflow-y: auto;
  background: white;
  border-left: 1px solid #e8e8e8;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.empty-icon {
  margin-bottom: 16px;
  font-size: 48px;
}

.empty-text {
  font-size: 14px;
}
</style>
